package com.wonderful.mall.order.web;

import com.wonderful.mall.order.service.OrderService;
import com.wonderful.mall.order.vo.OrderConfirmVo;
import com.wonderful.mall.order.vo.OrderSubmitVo;
import com.wonderful.mall.order.vo.SubmitOrderResponseVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Resource
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", confirmVo);
        System.out.println(confirmVo+"\n");
        return "confirm";
    }

    /**
     * 下单功能
     *
     * @param vo 订单提交的数据
     * @return 返回到支付选择页，如果失败，回到订单确认页
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {
        SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
        if (responseVo.getCode() == 0) {
            model.addAttribute("submitOrderResp", responseVo);
            return "pay";
        } else {
            String msg = "下单失败：";
            switch (responseVo.getCode()){
                case 1: msg+="订单信息过期";break;
                case 2: msg+="商品价格发生变化";break;
                case 3: msg+="库存锁定失败";break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.wonderfulmall.com/toTrade";
        }
    }
}
